package com.wlf.aiinterview.aop;

import com.wlf.aiinterview.annotation.CheckAuth;
import com.wlf.aiinterview.common.ErrorCode;
import com.wlf.aiinterview.constant.UserConstant;
import com.wlf.aiinterview.exception.BusinessException;
import com.wlf.aiinterview.model.pojo.User;
import com.wlf.aiinterview.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class AuthInterceptor {
    //切面
    @Around("@annotation(checkAuth)")
    public Object dointerceptor(ProceedingJoinPoint point, CheckAuth checkAuth) throws Throwable {
        //获取注解上的人物
        String role = checkAuth.role();
        // 根据session获取登录的角色
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User user = (User) request.getSession().getAttribute(UserConstant.SESSIONKEY);
        System.out.println(user);
        String userrole = null;
        if (user != null) {
            userrole = user.getUserrole();
        }
        //根据两个角色判断
        if (!role.equals(userrole)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问");
        }
        return point.proceed();
    }
}
